package com.alex.monitor.starter.demo.custom.alarm;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alex.monitor.core.alarm.impl.AbstractMonitorAlarm;
import com.alex.monitor.core.properties.AlexMonitorProperties;
import com.alex.monitor.core.properties.AlexMonitorProperties.HttpConfig;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 演示基于飞书即时通讯工具的自定义报警器
 *
 * @author Alex.Liu
 * @date: 2025-02-19 09:23
 * @since 1.0.0
 */
@Slf4j
@Component
public class FeishuRobotMonitorAlarm extends AbstractMonitorAlarm {

    private final HttpConfig config;

    public FeishuRobotMonitorAlarm(AlexMonitorProperties alexMonitorProperties) {
        super(alexMonitorProperties);
        this.config = alexMonitorProperties.getHttp();
    }

    @Override
    protected void doAlarm(String tag, JSONObject message) {
        HttpRequest request = HttpUtil.createPost(config.getUrl());
        request.addHeaders(config.getHeaders());
        request.contentType(ContentType.JSON.getValue());
        request.charset(config.getDefaultEncoding());
        JSONObject body = new JSONObject();
        JSONObject content = new JSONObject();
        content.put("text", message.toJSONString());
        body.put("content", content.toJSONString());
        body.put("msg_type", "text");
        request.body(body.toJSONString());
        try (HttpResponse response = request.execute()) {
            log.debug("{}", response.body());
            if (!response.isOk()) {
                log.error("alarm error url:{} status={}", config.getUrl(), response.getStatus());
            }
        } catch (Exception e) {
            log.error("alarm error url:{}", config.getUrl(), e);
        }
    }

}